﻿package org.dm.general
{
	import flash.display.Sprite;
	import org.dm.utils.Iterator;
	import org.dm.utils.Map;
	
	public final class ClassGather
	{
		private static var _instance:ClassGather = null;
		private var container:org.dm.utils.Map = new org.dm.utils.Map();
		
		public static function get instance():ClassGather 
		{ 
			if (_instance == null)
			{
				_instance = new ClassGather();
			}
			return _instance; 
		}
		
		public function ClassGather()
		{
			if(_instance!=null)
			{
				throw new Error("SingletonFactory is Singleton");
			}
		}
		
		public static function tryClass(name:String,cla:Class):* 
		{
			var cl:* = ClassGather.getClass(name);
			if(cl==null)
			{
				cl = new cla();
				ClassGather.reg(name,cl);
			}
			return cl;
		}
	
		public static function getClass(name:String):Class
		{
			var ins:ClassGather = instance;
			
			var iter:org.dm.utils.Iterator = ins.container.find(name);
			if(iter!=ins.container.end)
			{
				return iter.data;
			}			
			return null;
		}
		
		public static function getInstance(name:String,pars:Array=null):*
		{
			var ins:ClassGather = instance;
			
			var iter:org.dm.utils.Iterator = ins.container.find(name);
			if(iter!=ins.container.end)
			{
				return new iter.data;
			}
			throw new Error("This class is not exist!");
			return null;
		}
		
		public static function reg(name:String,pObj:*):Boolean
		{
			var ins:ClassGather = instance;
			
			var iter:org.dm.utils.Iterator = ins.container.find(name);
			if(iter!=ins.container.end)
			{
				return iter.data===pObj;
			}
			
			ins.container.insert(name,pObj);
			return true;
		}
		
		public static function unReg(name:String,pObj:*):Boolean
		{
			var ins:ClassGather = instance;
			
			var iter:org.dm.utils.Iterator = ins.container.find(name);
			if(iter!=ins.container.end)
			{
				if(iter.data===pObj)
				{
					ins.container.erase(iter);
					return true;
				}
			}
			
			return false;
		}
	}
}